import axios from "axios";

const instance = axios.create({
    baseURL: '/auth',
    timeout: 10000
})

// request interceptor
instance.interceptors.request.use(config => {
    // Add authorization header 从cookie获取
    const token = document.cookie.replace(/(?:(?:^|.*;\s*)satoken\s*=\s*([^;]*).*$)|^.*$/, "$1");
    console.log('get token from cookie', token)
    if (token != null && token.length > 0) {
        config.headers['satoken'] = 'Bearer ' + token;
    } else {
        // 获取当前url
        const currentUrl = window.location.href;
        // 重定向到sso项目（5100端口）的登录页
        window.location.href = 'http://localhost:5100/sign-in?from:' + currentUrl;
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// response interceptor
instance.interceptors.response.use(response => {
    return response.data;
}, error => {
    return Promise.reject(error.response);
});

export default instance;